package beautiful.butterfly.server.httpserver.mvc.aop.interceptor.impl;


import beautiful.butterfly.server.httpserver.mvc.aop.Interceptor;
import beautiful.butterfly.server.httpserver.mvc.aop.InterceptorsAndActionExecute;
import beautiful.butterfly.server.httpserver.mvc.core.ActionContext;
import beautiful.butterfly.server.httpserver.mvc.http.Request;
import beautiful.butterfly.server.httpserver.mvc.http.Session;
import beautiful.butterfly.server.httpserver.mvc.render.Render;
import beautiful.butterfly.server.httpserver.mvc.render.TextRender;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

/**
 * 进行是否登录判断,如果需要进行权限鉴别则需要其他的业务控制
 */
public class LoginInterceptor implements Interceptor {

    public static String msg = null;
    /**
     * 框架绑定的一个登录验证的属性
     */
    public static String LoginState = "Login";

    static {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "-100");// 表示没有登录状态
        map.put("msg", "请先登录");
        Gson gson = new Gson();
        msg = gson.toJson(map);
    }

    public Render doIt(InterceptorsAndActionExecute interceptorsAndActionExecute) {
        Request request = ActionContext.getRequest();
        Session session = request.getSession();
        if (session != null && session.getAttribute(LoginState) != null) {
            try {
                return interceptorsAndActionExecute.invoke();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            String requestType = request.getHeader("X-Requested-With");
            if (requestType != null && "XMLHttpRequest".equals(requestType)) {

                String test_login = request.getParameter("test_login");
                if (test_login != null && !"".equals(test_login)) {
                    return null;
                } else {
                    return new TextRender("");
                }
            } else {

                return null;
            }

        }
    }

}
